import {loginByUsername, getInfo, logOut} from '@/utils/login'
import {setToken, getToken, removeToken} from '@/utils/auth'

const user = {
    state:{
        user: {},
        roles: {},
        token: getToken()
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_INFO: (state, data) => {
            state.user = data
        },
        SET_ROLE: (state, role) => {
            state.roles = role
        }
    },
    actions: {
        // 登录
        LoginByUsername({commit}, data){
            return new Promise((resolve, reject) => {
                loginByUsername(data.username, data.password).then(res => {

                    commit('SET_TOKEN', res.data.token)
                    commit('SET_INFO', res.data.user)
                    setToken(res.data.token)
                    resolve()
                }).catch(error =>{
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetInfo({commit}){
            return new Promise((resolve, reject) => {
                getInfo().then(res => {

                    commit('SET_ROLE', res.data.id)
                    resolve(res.data.component)
                })
            }).catch(error => {
                reject(error)
            })
        },

        // 前端 登出
        LogOut({ commit }) {
            return new Promise(resolve => {
                logOut().then(() => {
                    commit('SET_TOKEN', '')
                    removeToken()
                    resolve()
                })
            })
        },
    }
}

export default user
